<?php

require_once eCMS_DIR . '/app/lib/SafeSQL/SafeSQL.class.php';

class MySQLConnection {
    
	// Speichert die Instanz der Klasse
    private static $instance;
    
    private static $mysql_id;
	private static $mysql_lastQuery;
	private static $mysql_numQuerys;
 
	private static $SafeSQL;
	
    // Ein private Konstruktor; verhindert die direkte Erzeugung des Objektes
    private function __construct() {
    	
		$cfg = Runtime::getConfiguration();
    			
    	self::$mysql_id = @mysql_connect($cfg['mysql_host'], $cfg['mysql_user'], $cfg['mysql_pass']);
		@mysql_select_db($cfg['mysql_db'], self::$mysql_id);  

		self::$SafeSQL = new SafeSQL_MySQL(self::$mysql_id);
    }

    /**
     * Returns the Singleton-Instance of the Class
     *
     * @return MySQLConnection
     */
    public static function getInstance() {
    	
        if (!isset(self::$instance)) {
            $c = __CLASS__;
            self::$instance = new $c;
        }

        return self::$instance;
    }

        // Halte Benutzer vom Klonen der Instanz ab
    public function __clone() {
    	
        trigger_error('Klonen ist nicht erlaubt.', E_USER_ERROR);
    }
    
    // Beispielmethode
    public function query($sql, $vars="") {
        $sql = self::$SafeSQL->query($sql, $vars);
    	
    	self::$mysql_lastQuery = $sql;
    	self::$mysql_numQuerys++;
        return @mysql_query($sql);
    }
    
    public function insert($sql, $vars="") {
        self::$mysql_lastQuery = $sql;
        
        self::query($sql, $vars);
    	return @mysql_insert_id(self::$mysql_id);
    }
	
    public function update($sql, $vars="") {
        self::$mysql_lastQuery = $sql;
        
        self::query($sql, $vars);
    	return @mysql_affected_rows(self::$mysql_id)>0;
    	
    }
    
    public function delete($sql, $vars="") {
        self::$mysql_lastQuery = $sql;
        
        self::query($sql, $vars);
    	return @mysql_affected_rows(self::$mysql_id)>0;
    	
    }
    
	public function quickQuery($sql, $vars="") {
        self::$mysql_lastQuery = $sql;
        		
		$res = self::query($sql, $vars);
		if(@mysql_num_fields($res)>1) {
			return @mysql_fetch_array($res);
		}
		else {
			return @mysql_result($res, 0);
		}
		
	}
	
	public function testConnection() {

		$cfg = Runtime::getConfiguration();
		
		return self::quickQuery('SELECT * FROM ' . $cfg['table_prefix'] . 'SecurityUser')!='';	
	}
	
	public function getLastQuery() {
		return self::$mysql_lastQuery;
	}
	
	public function getNumQuerys() {
		return self::$mysql_numQuerys;
	}
	
	public function getLinkId() {
		return self::$mysql_id;
	}
}

?>